//
//  JHBookUnitDetailView.m
//  JuniRengLish_iOS
//
//  Created by Maiyou on 2019/5/16.
//  Copyright © 2019 revogi. All rights reserved.
//

#import "JHBookUnitDetailView.h"
#import "JHBookUnitTableViewCell.h"
#import "wslAnalyzer.h"
#import "wslLrcEach.h"
#import "JHPreferencesInfoModel.h"

@interface JHBookUnitDetailView ()
{
    id _playerTimeObserver;
}
//当前歌词所在位置
@property (nonatomic,assign)  NSInteger currentRow;
@property (nonatomic,assign)  BOOL isDragging;

@end

@implementation JHBookUnitDetailView

- (instancetype)initWithFrame:(CGRect)frame
{
    if ([super initWithFrame:frame])
    {
        self.frame = frame;
        self.currentRow = -1;
        [self addSubview:self.tableView];
    }
    return self;
}

- (void)setBookid:(NSString *)bookid
{
    _bookid = bookid;
    
    [self getDataList];
    
    [self playControl];
}

- (void)getDataList
{
    wslAnalyzer *  analyzer = [[wslAnalyzer alloc] init];
    analyzer.isWord = !self.isBook;
    NSString * path = [NSString stringWithFormat:@"%@/%@/%@", [JHFileManger getDocumentsPath], self.bookid, self.textFileName];
    self.dataArray =  [analyzer analyzerLrcBylrcString:[NSString  stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]];
    [self.tableView reloadData];
}

- (AVPlayer *)player{
    
    if (_player == nil) {
        NSString * path = [NSString stringWithFormat:@"%@/%@/%@.mp3", [JHFileManger getDocumentsPath], self.bookid, self.mp3Name];
        _player = [[AVPlayer alloc] initWithURL:[NSURL fileURLWithPath:path]];
        _player.volume = 1;
    }
    return _player;
}

- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc] initWithFrame:self.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 50;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.tableFooterView = [UIView new];
    }
    return _tableView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifier = @"JHBookUnitTableViewCell";
    JHBookUnitTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell = [[NSBundle mainBundle] loadNibNamed:identifier owner:self options:nil].firstObject;
    }
    cell.dataArray = self.dataArray;
    cell.currentVC = self.currentVC;
    cell.isBook = self.isBook;
    cell.explainButton.tag = indexPath.row;
    NSInteger fontSize = [JHPreferencesInfoModel shareInstance].fontSize;
    if ([JHPreferencesInfoModel shareInstance].fontStyle == 10 || [JHPreferencesInfoModel shareInstance].fontStyle == 12)
    {
        cell.lrc_en_label.font = [UIFont systemFontOfSize:fontSize + 2];
        cell.lrc_ch_label.font = [UIFont systemFontOfSize:fontSize];
    }
    else
    {
        cell.lrc_en_label.font = [UIFont fontWithName:@"HiraginoSansGB" size:fontSize];
        cell.lrc_ch_label.font = [UIFont fontWithName:@"HiraginoSansGB" size:fontSize];
    }
    wslLrcEach   * eachLrc = self.dataArray[indexPath.row];
    cell.lrc_en_label.text = eachLrc.lrc_en;
    cell.lrc_ch_label.text = eachLrc.lrc_ch;
    if (self.isTranslate)
    {
        cell.lrc_ch_label.text = @"";
    }
    if (!self.isBook)
    {
        UILongPressGestureRecognizer * longPressGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(cellLongPress:)];
        longPressGesture.minimumPressDuration = 1.0f;//设置长按时间
        [cell addGestureRecognizer:longPressGesture];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    wslLrcEach * lrc = self.dataArray[indexPath.row];
    [self.player seekToTime:CMTimeMake(lrc.time, 1)];
    
    [self changeLrcShowStatus:indexPath.row];
    [self.player play];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(selectRowPlay:)]) {
        [self.delegate selectRowPlay:self.player];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    _isDragging = YES;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (!decelerate) {
        _isDragging = NO;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    _isDragging = NO;
}

- (void)cellLongPress:(UILongPressGestureRecognizer *)longRecognizer
{
    if (longRecognizer.state == UIGestureRecognizerStateBegan)
    {
        //成为第一响应者，需重写该方法
        [self becomeFirstResponder];
        
        CGPoint location = [longRecognizer locationInView:self.tableView];
        NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
        //添加数据到数据库
        wslLrcEach   * eachLrc = self.dataArray[indexPath.row];
        if ([eachLrc.lrc containsString:@"\n"])
        {
            JHKeyValueStorage * storage = [[JHKeyValueStorage alloc] init];
            [storage insertValue:eachLrc.lrc intoTable:@"NewWords"];
            [DJToast showBottomToast:@"已添加到生词本~"];
        }
    }
}

//播放控制和监测
- (void)playControl{
    
    //后台播放音频设置,需要在Capabilities->Background Modes中勾选Audio,Airplay,and Picture in Picture
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
    
    WEAKSELF
    _playerTimeObserver = [weakSelf.player addPeriodicTimeObserverForInterval:CMTimeMake(0.1*30, 30) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        CGFloat currentTime = CMTimeGetSeconds(time);
        
        CMTime total = weakSelf.player.currentItem.duration;
        CGFloat totalTime = CMTimeGetSeconds(total);
        
        if (!weakSelf.isDragging) {
            
            //歌词滚动显示
            for ( int i = (int)(self.dataArray.count - 1); i >= 0 ;i--) {
                wslLrcEach * lrc = self.dataArray[i];
                if (lrc.time < currentTime) {
                    [self changeLrcShowStatus:i];
//                    [self.tableView reloadData];
                    break;
                }
            }
        }
    }];
}

- (void)changeLrcShowStatus:(int)index
{
    NSIndexPath * pastIndexPath = [NSIndexPath indexPathForRow: self.currentRow inSection:0];
    JHBookUnitTableViewCell * pastCell = [self.tableView cellForRowAtIndexPath:pastIndexPath];
    pastCell.lrc_en_label.textColor = [UIColor darkGrayColor];
    pastCell.lrc_ch_label.textColor = [UIColor darkGrayColor];
    
    self.currentRow = index;
    NSIndexPath * currentIndexPath = [NSIndexPath indexPathForRow: self.currentRow inSection:0];
    JHBookUnitTableViewCell * currentCell = [self.tableView cellForRowAtIndexPath:currentIndexPath];
    currentCell.lrc_en_label.textColor = [UIColor blueColor];
    currentCell.lrc_ch_label.textColor = [UIColor blueColor];
    [self.tableView scrollToRowAtIndexPath:currentIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}

- (void)moviePlayDidEnd:(NSNotification*)notification
{
    if ([JHPreferencesInfoModel shareInstance].playMode == 30)
    {
        AVPlayerItem * item = [notification object];
        [item seekToTime:kCMTimeZero];
        [self.player play];
    }
    else
    {
        if (self.delegate && [self.delegate respondsToSelector:@selector(playEnd:)])
        {
            [self.delegate playEnd:self];
        }
    }
}

//移除观察者
- (void)removeObserver{
    
    [self.player removeTimeObserver:_playerTimeObserver];
    _playerTimeObserver = nil;
}

- (void)dealloc{
    [self removeObserver];
}

@end
